/*
 *	xarray.c
 *	  part of the xlibrary by SunDEV (http://sundev.890m.com)
 *
 *	Changelog :
 *	  ##-##-## : First public release
 *
 */

#include <stdlib.h>
#include <stdio.h>
#include <string.h>

// common
#include "xcommon.h"

// local
#include "xmalloc.h"
#include "xassert.h"

#include "xarray.h"

void da_init(sDA *a, size_t nae, size_t se) {
    XASSERT(a);

    if(se) {
        a->se=se;
        a->ne=0;
        a->nae=nae;
        a->data=nae?xmalloc(nae*se):NULL;
    }
    else bzero(a, sizeof(sDA));
}

size_t da_add(sDA *a, void *e) {
    XASSERT(a);

    if(a->ne>=a->nae) {
        if(a->nae) a->nae*=2;
        else a->nae=2;

        a->data=xrealloc(a->data, a->nae*a->se);
    }

    if(e) memcpy(a->data+a->ne*a->se, e, a->se);
    else bzero(a->data+a->ne*a->se, a->se);

    return a->ne++;
}

void da_trim(sDA *a) {
    XASSERT(a);

    if(a->nae>a->ne) {
        a->data=xrealloc(a->data, a->ne*a->se);
        a->nae=a->ne;
    }
}

void da_free(sDA *a) {
    XASSERT(a);

    if(a->data) xfree(a->data);
}

